const md5 = require('blueimp-md5')
const moment = require('moment')
const db = require('../modules/db')
const sqlHelper = require('../utilities/sqlhelper')

//查询邮箱是有存在
exports.list = async (req, res, next) => {
  try {
    const andConditionStr = sqlHelper.andCondtion(req.query)
  sqlStr = `
    SELECT * FROM users WHERE ${andConditionStr}
  `
  res.status(200).json(await db.query(sqlStr))
  } catch(err) {
    next(err)
  }
}


exports.create = async (req, res, next) => {
  const body = req.body
  const sqlStr =`INSERT INTO users(username, password, email, nickname ,avatar, gender, create_time, modify_time)
  VALUES(
    '${body.email}',
    '${md5(md5(body.password))}',
    '${body.email}',
    '${body.nickname}',
    'default-avatar.png',
    0,
    '${moment().format('YYYY-MM-DD  h:mm:ss ')}',
    '${moment().format('YYYY-MM-DD hh:mm:ss')}'
  )`

//一旦报错就进入 catch
  try{
    const ret = await db.query(sqlStr)
    const [users] = await db.query(`SELECT * FROM users WHERE id='${ret.insertId}'`)
    res.status(201).json(users)
  } catch (err) {
    res.status(500).json({
      error: err.message
    })
  }
}

exports.update = async (req, res, next) => {
  try {
    const {id} = req.params
    const {nickname, gender} = req.body
    const sqlStr = `UPDATE users SET nickname='${nickname}', gender='${gender}', modify_time = '${moment().format('YYYY-MM-DD hh:mm:ss')}'
     WHERE id=${id} `
    await db.query(sqlStr)
    const [user] = await db.query(`SELECT * FROM users WHERE id = ${id}`)
    res.status(200).json(user)
  } catch (err) {
    next(err)
  }

}

exports.delete = (req, res, next) => {

}


